package com.gofunbuy.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.gofunbuy.util.GoFunBuyUtils.GoFunBuyInterface;
import com.gofunbuy.util.GoFunBuyUtils.IntegrationXML;
import com.gofunbuy.util.GoFunBuyUtils.LoginXML;
import com.gofunbuy.util.GoFunBuyUtils.PayHistoryXML;
import com.gofunbuy.util.GoFunBuyUtils.RegistXML;
import com.gofunbuy.util.XmlUtil;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class HttpClientImpl implements GoFunBuyInterface {

	private static final String TAG = "PRURadio";
	private static final int DEFAULT_TIME_OUT = 15 * 1000;
	private static int bigFileSize = 50 * 1024 * 1024;// 大文件限制
	public static final String KEY_NETWORK_ERROR = "network_error";

	public static final String HTTP_SERVICE = "http://www.eye4gift.com/gofun/";
	public static final String HTTP_REGIST = HTTP_SERVICE + "app_buyer_reg.php";
	public static final String HTTP_LOGIN = HTTP_SERVICE
			+ "app_buyer_login.php";// 登陆
	public static final String HTTP_GET_INTEGRATION = HTTP_SERVICE
			+ "app_get_pointinfo.php";// 获取积分和捐赠总额
	public static final String HTTP_GET_PAY_HISTORY = HTTP_SERVICE
			+ "app_get_receipt.php";// 获取积分和捐赠总额

	public static HttpClientImpl mHttpClient = null;
	public Context mContext;

	public HttpClientImpl(Context context) {
		this.mContext = context;
	}

	public static HttpClientImpl getInstance(Context context) {
		if (mHttpClient == null)
			mHttpClient = new HttpClientImpl(context);
		return mHttpClient;
	}

	/**
	 * 注册
	 * 
	 * @param handler
	 * @param urlString
	 * @param params
	 * @return
	 * @throws IOException
	 * @throws JSONException
	 */
	public RegistXML RegistService(Handler handler,
			HashMap<String, String> params) throws IOException, JSONException {
		Log.d(TAG, "HttpClient::RegistService>>>>>>>>>>>>>>>>>>>>>>>>>>params:"
				+ params);
		// LoginXML vo = null;
		InputStream is = httpPostParams(HTTP_REGIST, params);
		// Log.d(TAG,
		// "HttpClient::loginService>>>>>>>>>>>>>>>>>>>>>>>>>>content:"
		// + content);
		// ArrayList<MessageFromService> list = null;
		if (is == null) {
			Message msg = new Message();
			msg.what = MSG_NETWORD_ERROR;
			handler.sendMessage(msg);
		} else {
			// JSONObject jsonObj = new JSONObject(content);
			return XmlUtil.getRegistItem(is);
		}
		return null;

	}

	/**
	 * 登陆服务器
	 * 
	 * @param handler
	 * @param urlString
	 * @param params
	 * @return
	 * @throws IOException
	 * @throws JSONException
	 */
	public LoginXML loginService(Handler handler, HashMap<String, String> params)
			throws IOException, JSONException {
		Log.d(TAG, "HttpClient::loginService>>>>>>>>>>>>>>>>>>>>>>>>>>params:"
				+ params);
		// LoginXML vo = null;
		InputStream is = httpPostParams(HTTP_LOGIN, params);
		// Log.d(TAG,
		// "HttpClient::loginService>>>>>>>>>>>>>>>>>>>>>>>>>>content:"
		// + content);
		// ArrayList<MessageFromService> list = null;
		if (is == null) {
			Message msg = new Message();
			msg.what = MSG_NETWORD_ERROR;
			handler.sendMessage(msg);
		} else {
			// JSONObject jsonObj = new JSONObject(content);
			return XmlUtil.getLoginItem(is);
		}
		return null;

	}

	/**
	 * 登陆服务器
	 * 
	 * @param handler
	 * @param urlString
	 * @param params
	 * @return
	 * @throws IOException
	 * @throws JSONException
	 */
	public IntegrationXML getIntegrationAndDonation(Handler handler,
			HashMap<String, String> params) throws IOException, JSONException {
		Log.d(TAG,
				"HttpClient::getIntegrationAndDonation>>>>>>>>>>>>>>>>>>>>>>>>>>params:"
						+ params);
		InputStream is = httpPostParams(HTTP_GET_INTEGRATION, params);
		if (is == null) {
			Message msg = new Message();
			msg.what = MSG_NETWORD_ERROR;
			handler.sendMessage(msg);
		} else {
			return XmlUtil.getDonationItem(is);
		}
		return null;

	}

	/**
	 * 登陆服务器
	 * 
	 * @param handler
	 * @param urlString
	 * @param params
	 * @return
	 * @throws IOException
	 * @throws JSONException
	 */
	public ArrayList<PayHistoryXML> getReceiptList(Handler handler,
			HashMap<String, String> params) throws IOException, JSONException {
		Log.d(TAG,
				"HttpClient::getReceiptList>>>>>>>>>>>>>>>>>>>>>>>>>>params:"
						+ params);
		InputStream is = httpPostParams(HTTP_GET_PAY_HISTORY, params);
		if (is == null) {
			Message msg = new Message();
			msg.what = MSG_NETWORD_ERROR;
			handler.sendMessage(msg);
		} else {
			return XmlUtil.getReceiptsList(is);
		}
		return null;

	}

	/**
	 * http请求
	 * 
	 * @param urlString
	 * @param params
	 * @return
	 * @throws IOException
	 */
	public String httpRequest(String urlString, HashMap<String, String> params)
			throws IOException {
		String Content = "";
		InputStream content = null;
		BufferedReader in = null;
		HttpURLConnection httpUc = null;
		StringBuilder sb = new StringBuilder();
		try {
			StringBuffer paraStr = new StringBuffer();
			if (params != null && !"".equals(params)) {
				for (String key : params.keySet()) {
					paraStr.append("&").append(key).append("=")
							.append(params.get(key));
				}
				paraStr.deleteCharAt(0);
			}
			URL url = new URL(urlString + "?" + paraStr.toString());//
			Log.d(TAG, "HttpClient::httpRequest url:" + urlString + "?"
					+ paraStr.toString());
			httpUc = (HttpURLConnection) url.openConnection();
			httpUc.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.5");//
			httpUc.setRequestProperty("User-Agent", "Android Application:2.1");
			httpUc.setRequestProperty("Connection", "close");
			httpUc.setConnectTimeout(DEFAULT_TIME_OUT);
			httpUc.setReadTimeout(DEFAULT_TIME_OUT);
			httpUc.setRequestProperty("Charsert", "UTF-8");
			httpUc.connect();
			int code = httpUc.getResponseCode();
			if (code == HttpStatus.SC_OK) {
				content = (InputStream) httpUc.getInputStream();
				in = new BufferedReader(new InputStreamReader(content, "UTF-8"));
				while ((Content = in.readLine()) != null) {
					sb.append(Content + "\r\n");
				}
			} else {
				return KEY_NETWORK_ERROR;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return KEY_NETWORK_ERROR;
		} catch (ConnectException e) {
			e.printStackTrace();
			return KEY_NETWORK_ERROR;
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			return KEY_NETWORK_ERROR;
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return KEY_NETWORK_ERROR;
		} catch (SocketException e) {
			e.printStackTrace();
			return KEY_NETWORK_ERROR;
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
			return KEY_NETWORK_ERROR;
		} catch (Exception e) {
			e.printStackTrace();
			return KEY_NETWORK_ERROR;
		} finally {
			// Log.d(TAG, "close httpRequest>>>>>>>>>>>>>");
			if (in != null) {
				in.close();
			}
			if (content != null) {
				content.close();
			}
			if (httpUc != null) {
				httpUc.disconnect();
			}
		}
		return sb.toString();
	}

	private String HttpPostData(String uri, HashMap<String, String> params) {
		try {
			StringBuilder result = new StringBuilder();
			DefaultHttpClient mHttpClient = new DefaultHttpClient();

			HttpPost httppost = new HttpPost(uri);
			List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
			if (params != null && !"".equals(params)) {
				for (String key : params.keySet()) {
					pairs.add(new BasicNameValuePair(key, params.get(key)));
				}
			}
			httppost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
			Log.v(TAG, "http post:" + httppost.getURI().toString());
			mHttpClient.getParams().setIntParameter(
					HttpConnectionParams.SO_TIMEOUT, 10 * 1000);
			mHttpClient.getParams().setIntParameter(
					HttpConnectionParams.CONNECTION_TIMEOUT, 10 * 1000);

			HttpResponse httpResponse = mHttpClient.execute(httppost);
			// 检验状态码，如果成功接收数据
			int code = httpResponse.getStatusLine().getStatusCode();
			if (code == HttpStatus.SC_OK) {
				// Header[] headers = httpResponse.getAllHeaders();
				HttpEntity entity = httpResponse.getEntity();
				// Header header = httpResponse.getFirstHeader("content-type");
				// 读取服务器返回的json数据（接受json服务器数据）
				InputStream inputStream = entity.getContent();
				InputStreamReader inputStreamReader = new InputStreamReader(
						inputStream, "UTF-8");
				BufferedReader reader = new BufferedReader(inputStreamReader);// 读字符串用的。
				String s;
				while (((s = reader.readLine()) != null)) {
					result.append(s);
					Log.d(TAG, "HttpClient::HttpPostData=======s:" + s);
				}
				reader.close();// 关闭输入流
				inputStreamReader.close();
				inputStream.close();
				return result.toString();
			} else {
				return KEY_NETWORK_ERROR;
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return KEY_NETWORK_ERROR;
	}

	private InputStream HttpPostData3(String uri, HashMap<String, String> params) {
		try {
			StringBuilder result = new StringBuilder();
			DefaultHttpClient mHttpClient = new DefaultHttpClient();

			HttpPost httppost = new HttpPost(uri);
			List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
			if (params != null && !"".equals(params)) {
				for (String key : params.keySet()) {
					pairs.add(new BasicNameValuePair(key, params.get(key)));
				}
			}
			httppost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
			mHttpClient.getParams().setIntParameter(
					HttpConnectionParams.SO_TIMEOUT, 10 * 1000);
			mHttpClient.getParams().setIntParameter(
					HttpConnectionParams.CONNECTION_TIMEOUT, 10 * 1000);

			HttpResponse httpResponse = mHttpClient.execute(httppost);
			// 检验状态码，如果成功接收数据
			int code = httpResponse.getStatusLine().getStatusCode();
			if (code == HttpStatus.SC_OK) {
				// Header[] headers = httpResponse.getAllHeaders();
				HttpEntity entity = httpResponse.getEntity();
				// Header header = httpResponse.getFirstHeader("content-type");
				// 读取服务器返回的json数据（接受json服务器数据）
				InputStream inputStream = entity.getContent();
				return inputStream;
			} else {
				return null;
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String GetFileName(String url) {
		StringTokenizer st = new StringTokenizer(url, "/");
		while (st.hasMoreTokens()) {
			url = st.nextToken();
		}
		return url;
	}

	// public void DownFileFromService(Handler handler, int pose, String
	// urlString) {
	// Log.d(TAG,
	// "HttpClient::DownFileFromService>>>>>>>>>>>>>>>>>>>>>>>>>>urlString:"
	// + urlString);
	// try {
	// URL url = new URL(urlString);
	// URLConnection connection = url.openConnection();
	// if (connection.getReadTimeout() == 5) {
	// Log.i(TAG, "当前网络有问题");
	// // return;
	// }
	// InputStream inputStream = connection.getInputStream();
	// // 文件的保存路径和和文件名其中Nobody.mp3是在手机SD卡上要保存的路径，如果不存在则新建
	// File file1 = new File(PruUtil.DOWNLOAD_FILE_NAME_PRE);
	// if (!file1.exists()) {
	// file1.mkdir();
	// }
	// String savePathString = PruUtil.DOWNLOAD_FILE_NAME_PRE + "/"
	// + GetFileName(urlString);
	// File file = new File(savePathString);
	// if (!file.exists()) {
	// file.createNewFile();
	// }
	// // 向SD卡中写入文件,用Handle传递线程
	// int FileLength;
	// int DownedFileLength = 0;
	// FileOutputStream outputStream = new FileOutputStream(file);
	// byte[] buffer = new byte[1024];
	// FileLength = connection.getContentLength();
	// Log.v(TAG, "HttpClientImpl::total:" + FileLength);
	// int i = 0, len = 0;
	// handler.sendMessage(handler.obtainMessage(MSG_SEEKBAR_DOWNLOADING,
	// FileLength, 0));
	// while (DownedFileLength < FileLength) {
	// len = inputStream.read(buffer);
	// DownedFileLength += len;
	// outputStream.write(buffer, 0, len);
	// if (i % 50 == 0)
	// handler.sendMessage(handler.obtainMessage(
	// MSG_SEEKBAR_DOWNLOADING, DownedFileLength,
	// FileLength));
	// i++;
	// }
	// outputStream.close();
	// inputStream.close();
	// handler.sendMessage(handler.obtainMessage(MSG_SEEKBAR_DOWNLOADING,
	// DownedFileLength, FileLength));
	// handler.sendMessage(handler.obtainMessage(
	// MSG_ADAPTER_DOWNLOAD_RESPONSE, pose, 0, savePathString));
	// return;
	//
	// } catch (FileNotFoundException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// } catch (IOException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// handler.sendMessage(handler.obtainMessage(MSG_DOWNLOAD_FAILED_ERROR));//
	// 下载失败
	//
	// }

	private static InputStream httpPostParams(String url,
			HashMap<String, String> params) {
		// String result = null;
		InputStream is = null;
		try {
			// 模拟器测试时，请使用外网地址
			// String url = "http://5billion.com.cn/post.php";
			// Map<String, String> data = new HashMap<String, String>();
			// data.put("name", "webabcd");
			// data.put("salary", "100");
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			ArrayList<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
			for (Map.Entry<String, String> m : params.entrySet()) {
				postData.add(new BasicNameValuePair(m.getKey(), m.getValue()));
				Log.v("222", "name:" + m.getKey() + " value:" + m.getValue());
			}

			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData,
					HTTP.UTF_8);
			httpPost.setEntity(entity);

			HttpResponse response = httpClient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
				// HttpURLConnection.HTTP_OK
				HttpEntity httpEntity = response.getEntity();
				is = httpEntity.getContent();
				// result = convertStreamToString(is);
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return is;
	}

	// 辅助方法，用于把流转换为字符串
	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return sb.toString();
	}

	public static InputStream HttpPostData2(String uri,
			HashMap<String, String> params) {
		try {
			StringBuilder result = new StringBuilder();
			DefaultHttpClient mHttpClient = new DefaultHttpClient();

			HttpPost httppost = new HttpPost(uri);
			List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
			if (params != null && !"".equals(params)) {
				for (String key : params.keySet()) {
					pairs.add(new BasicNameValuePair(key, params.get(key)));
				}
			}
			httppost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
			mHttpClient.getParams().setIntParameter(
					HttpConnectionParams.SO_TIMEOUT, 10 * 1000);
			mHttpClient.getParams().setIntParameter(
					HttpConnectionParams.CONNECTION_TIMEOUT, 10 * 1000);

			HttpResponse httpResponse = mHttpClient.execute(httppost);
			// 检验状态码，如果成功接收数据
			int code = httpResponse.getStatusLine().getStatusCode();
			if (code == HttpStatus.SC_OK) {
				// Header[] headers = httpResponse.getAllHeaders();
				HttpEntity entity = httpResponse.getEntity();
				// Header header = httpResponse.getFirstHeader("content-type");
				// 读取服务器返回的json数据（接受json服务器数据）
				InputStream inputStream = entity.getContent();
				return inputStream;
			} else {
				return null;
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 以 DOM 方式解析 XML（xml 数据详见 res/raw/employee.xml）
	private HashMap<String, HashMap<String, String>> loginOrRegistParse2Map(
			String target, String firstRoot, String secondRoot) {
		try {
			DocumentBuilderFactory docFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			Document doc = docBuilder.parse(target);
			Element rootElement = doc.getDocumentElement();

			NodeList nodelist = rootElement.getChildNodes();
			int size = nodelist.getLength();
			HashMap<String, HashMap<String, String>> resultList = new HashMap<String, HashMap<String, String>>();
			for (int i = 0; i < size; i++) {
				NodeList employeeNodeList = rootElement
						.getElementsByTagName(firstRoot);
				HashMap<String, String> mMap = null;

				// resultList.put(key, value)
			}
			ArrayList<HashMap<String, String>> mResultArray = new ArrayList<HashMap<String, String>>();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * @param element
	 *            将要进行遍历的节点
	 */
	private HashMap<String, String> parse2Map(Element element) {
		NodeList nodelist = element.getChildNodes();
		int size = nodelist.getLength();
		HashMap<String, String> mMap = null;
		for (int i = 0; i < size; i++) {
			// 获取特定位置的node
			mMap = new HashMap<String, String>();
			Node element2 = (Node) nodelist.item(i);
			mMap.put(element2.getNodeName(), element2.getNodeValue());
		}
		return mMap;
	}
}
